<template lang="html">
    <div class="type-list">
        <myHeader>
            <div class="add-icon">
                <i class="iconfont icon-add" @click="addEventType"></i>
            </div>
        </myHeader>
        <div class="select-container">
            <van-tree-select
                style="height: 100%"
                :items="items"
                :main-active-index="mainActiveIndex"
                :active-id="activeId"
                @navclick="onNavClick"
                @itemclick="onItemClick"
            />
        </div>
        <confirm v-model="showAddType"
            title="添加消费类型"
            @on-cancel="onCancel"
            @on-confirm="onConfirm">
            <van-field v-model="addTypeText" :border="true" placeholder="请输入消费类型" />
        </confirm>
    </div>
</template>

<script>
import TreeSelect from 'vant/lib/tree-select'
import Field from 'vant/lib/field'
import { Confirm } from 'vux'
export default {
    data() {
        return {
            items: [],
            mainActiveIndex: 0,
            activeId: 0,
            showAddType: false,
            addTypeText: ''
        }
    },
    methods: {
        getList(){
            this.$vux.loading.show({
                text: '加载中'
            })
            this.$api.get('/charge/types').then(res => {
                this.$vux.loading.hide()
                this.items = res
            })
        },
        addEventType(){
            this.showAddType = true
            console.log(this.mainActiveIndex)
        },
        onCancel(){
            this.addTypeText = ''
        },
        onConfirm(){
            if (this.addTypeText === '') {
                this.$vux.toast.show({text: '请输入消费类型！'})
                return false
            }
            this.$api.post('/charge/add', {
                pid: this.items[this.mainActiveIndex]['id'],
                text: this.addTypeText
            }).then(res => {
                this.$vux.toast.show({text: '添加成功！'})
                this.getList()
            })
        },
        onNavClick(index) {
            this.mainActiveIndex = index;
        },
        onItemClick(data) {
            this.activeId = data.id;
        }
    },
    created(){
        this.getList()
    },
    components: {
        vanTreeSelect: TreeSelect,
        vanField: Field,
        Confirm
    }
}
</script>

<style lang="scss" scoped>
    .type-list {
        height: 100%;
        display: flex;
        flex-direction: column;
        .select-container{
            flex: 1;
        }
        .add-icon{
            font-size: .16rem;
            text-align: right;
            padding: 0 .1rem;
        }
    }
</style>
